package restlet.android;

import java.util.ArrayList;
import com.cse210.grocerwe.client.SItem;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;


public class ShoppingActivity extends Activity{
    private ShoppingListsAdapter2 m_adapter;
    private ListView listView;
    private SItem [] groupItems;
    private ArrayList<String> selectedGroupNames;
    private ArrayList<String> selectedGroupKeys;
    private final String TAG = "ShoppingActivity";
    //private ArrayList<SItem> groupItems = new ArrayList<SItem>();
    private final String user = UserCredentials.getUserName();
	private GrocerResource resource = new GrocerResource();
    private ArrayList<SelectedGroup> selectedGroups = new ArrayList<SelectedGroup>();
    private final boolean LIVE = true; 
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.shopping2);
	    listView = (ListView) findViewById(R.id.ShoppingIfacelistView);
	    Button DoneButton = (Button) findViewById(R.id.DoneShoppingButton);
	    Button CancelButton = (Button) findViewById(R.id.CancelShoppingButton);
        
	    /*LayoutInflater itemFactory = LayoutInflater.from(this);
        View ListItemView = itemFactory.inflate(R.layout.shopping_item_row, null);
	    CheckedTextView CheckedTv = (CheckedTextView) ListItemView.findViewById(R.id.ListText);
	    */
	    
	    ///
	    //ImageView OwnerImg = (ImageView) findViewById(R.id.ItemOwnerPic);
	    //Drawable d = this.getResources().getDrawable(R.drawable.user3);
	    //OwnerImg.setImageDrawable(d);  
	    ///
	    Log.v(TAG, "User in SA: " + user);
	    
	    Intent myIntent = getIntent();
	    selectedGroupNames = myIntent.getStringArrayListExtra("selected_groups_list");
	    selectedGroupKeys = myIntent.getStringArrayListExtra("selected_groupkeys_list");
	    /*
	    selectedGroups.clear(); 
	    m_adapter.clearList();
	    selectedGroupNames.clear();
	    selectedGroupKeys.clear();
	    */
	    int totalItems = 0;
	    for(int i = 0; i < selectedGroupNames.size(); i++)
	    {
	    	String groupName = selectedGroupNames.get(i);
	    	String groupKey = selectedGroupKeys.get(i);
	    	Log.v(TAG, "selected name: " + groupName);
	    	Log.v(TAG, "selected key: " + groupKey);
	    	groupItems = resource.retrieveList(groupKey);
	    	Log.v(TAG, "Item num: " + groupItems.length);
	    	for (SItem item: groupItems) {
	    		Log.v(TAG, "Adding into SelectedGroup class");
	    		Log.v(TAG, "Status: " + item.getStatus());
	    		if (item.getStatus() != 2) {
	    		    selectedGroups.add(new SelectedGroup(groupKey,item));
	    		    totalItems++;
	    		}
	    	}
	    }
	    
	    // At this point we have a flattened list of all items which are liable
	    // to be purchased. 
	    
	    //m_adapter = new ShoppingListsAdapter2(ShoppingActivity.this, R.layout.shopping_item, new ArrayList<String>());
	    m_adapter = new ShoppingListsAdapter2(ShoppingActivity.this, R.layout.shopping_item_row, new ArrayList<String>());
        listView.setAdapter(m_adapter);
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	    
        //Add items to the list adapter
        for(SelectedGroup selGroup: selectedGroups){ 
        	String Item = selGroup.getItem().getName();
        	String Type = selGroup.getItem().getType();
        	//int qty = selGroup.getItem().getQuantity();
        	String SQty = selGroup.getItem().getQuantitySize();
        	Log.v(TAG, "Item: " + Item);
            m_adapter.addGroup(Item + " - " + Type + " - " + SQty);
            /*Drawable d;
            d = ShoppingActivity.this.getResources().getDrawable(R.drawable.user1);
            CheckedTv.setCompoundDrawablesWithIntrinsicBounds(d, null, null, null);*/
        }
        m_adapter.notifyDataSetChanged();

        if(totalItems == 0)
        {
        	Toast.makeText(ShoppingActivity.this, "No Items to show.", Toast.LENGTH_LONG).show();
        }
    
	    DoneButton.setOnClickListener(new OnClickListener()
	    {            
	        @Override
	        public void onClick(View v)
	        {
	            Log.v(TAG, "Done Shopping and releaseing all lists");
                ShoppingActivity.this.buyMarkedItems();
	        }
	        
	    });	
	    
	    CancelButton.setOnClickListener(new OnClickListener()
	    {            
	        @Override
	        public void onClick(View v)
	        {
	            Log.v(TAG, "Canceling and releasing all lists");
                ShoppingActivity.this.ReleaseListsAndFinish();
	        }
	        
	    });
	    
	    
    }
	
    private void buyMarkedItems() {
    	ArrayList<SItem> items = new ArrayList<SItem>();
    	Log.v(TAG, "Size of item list: " + selectedGroups.size());
    	boolean items_selected = false;
        for (int i = 0; i < selectedGroups.size(); i++)
        {
            if(listView.isItemChecked(i))
            {
            	items_selected = true;
            	String groupKey = selectedGroups.get(i).getGroupKey();
            	items.add(selectedGroups.get(i).getItem());
            	Log.v(TAG, "To Buy: " + items.get(0).getName() + " " + groupKey);
                if (LIVE)
                {
                	Log.v(TAG, "Purchasing: " + items.get(0).getName() + "," + groupKey);
                    resource.purchaseItems(items);
                }
            	items.clear();
            }
        }
        if (items_selected) {
            // Here release all selected lists to unlock them and finish the activity
        	// But at least one entry has to be selected for this.
            this.ReleaseListsAndFinish();
        }
        else {
        	Toast.makeText(ShoppingActivity.this, "Nothing Selected. Please select at least one entry.", Toast.LENGTH_LONG).show();	
        }
    }
    
    private void ReleaseListsAndFinish() {
        String prevGroupKey = null;
        for (int i = 0; i < selectedGroups.size(); i++)
        {
        	String groupKey = selectedGroups.get(i).getGroupKey();
        	if (groupKey != prevGroupKey)
        	{
        		Log.v(TAG, "About to Release List: " + groupKey);
        		if(LIVE)
        		{
        		    Log.v(TAG, "Releasing list: " + groupKey);
                    resource.releaseList(groupKey, user);
        		}
        	}
        	prevGroupKey = groupKey;
        }
        finish();
    }
};
